import { useRequest } from 'ahooks';
import { message } from 'antd';
import type { Options } from 'ahooks/lib/useRequest/src/types';
import type { ResultData, RequestConfig } from '../types/api';

/**
 * 基础请求配置
 */
const baseConfig = {
  /** API 基础路径 */
  baseURL: '/api',
  /** 请求超时时间 */
  timeout: 10000,
  /** 默认请求头 */
  headers: {
    'Content-Type': 'application/json',
  },
};

/**
 * 模拟 fetch 请求函数
 * 在实际项目中，这里应该使用真实的 HTTP 客户端（如 axios）
 * @param url - 请求地址
 * @param options - 请求配置
 * @returns Promise<ResultData>
 */
const fetchRequest = async <T = any>(
  url: string,
  options: RequestInit = {}
): Promise<ResultData<T>> => {
  const { method = 'GET', body, headers, ...restOptions } = options;
  
  // 构建完整的请求地址
  const fullUrl = url.startsWith('http') ? url : `${baseConfig.baseURL}${url}`;
  
  try {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, Math.random() * 1000 + 500));
    
    // 这里应该是真实的网络请求
    // const response = await fetch(fullUrl, {
    //   method,
    //   headers: {
    //     ...baseConfig.headers,
    //     ...headers,
    //   },
    //   body: body ? JSON.stringify(body) : undefined,
    //   ...restOptions,
    // });
    
    // 模拟响应数据
    const mockResponse: ResultData<T> = {
      code: 200,
      message: '请求成功',
      data: {} as T,
      success: true,
    };
    
    return mockResponse;
  } catch (error) {
    throw new Error(`请求失败: ${error}`);
  }
};

/**
 * GET 请求封装
 * @param url - 请求地址
 * @param params - 查询参数
 * @param config - 请求配置
 * @returns useRequest hook
 */
export const useGet = <T = any>(
  url: string,
  params?: Record<string, any>,
  config?: RequestConfig & Options<ResultData<T>, any[]>
) => {
  const { loading = true, errorMessage = true, successMessage = false, ...restConfig } = config || {};
  
  return useRequest(
    async () => {
      const queryString = params ? new URLSearchParams(params).toString() : '';
      const requestUrl = queryString ? `${url}?${queryString}` : url;
      return fetchRequest<T>(requestUrl, { method: 'GET' });
    },
    {
      loadingDelay: loading ? 300 : undefined,
      onSuccess: (data) => {
        if (successMessage && data.success) {
          message.success(data.message || '操作成功');
        }
        config?.onSuccess?.(data);
      },
      onError: (error) => {
        if (errorMessage) {
          message.error(error.message || '请求失败');
        }
        config?.onError?.(error);
      },
      ...restConfig,
    }
  );
};

/**
 * POST 请求封装
 * @param url - 请求地址
 * @param config - 请求配置
 * @returns useRequest hook
 */
export const usePost = <T = any, P = any>(
  url: string,
  config?: RequestConfig & Options<ResultData<T>, [P]>
) => {
  const { loading = true, errorMessage = true, successMessage = true, ...restConfig } = config || {};
  
  return useRequest(
    async (data: P) => {
      return fetchRequest<T>(url, {
        method: 'POST',
        body: data,
      });
    },
    {
      manual: true,
      loadingDelay: loading ? 300 : undefined,
      onSuccess: (data) => {
        if (successMessage && data.success) {
          message.success(data.message || '操作成功');
        }
        config?.onSuccess?.(data);
      },
      onError: (error) => {
        if (errorMessage) {
          message.error(error.message || '操作失败');
        }
        config?.onError?.(error);
      },
      ...restConfig,
    }
  );
};

/**
 * PUT 请求封装
 * @param url - 请求地址
 * @param config - 请求配置
 * @returns useRequest hook
 */
export const usePut = <T = any, P = any>(
  url: string,
  config?: RequestConfig & Options<ResultData<T>, [P]>
) => {
  const { loading = true, errorMessage = true, successMessage = true, ...restConfig } = config || {};
  
  return useRequest(
    async (data: P) => {
      return fetchRequest<T>(url, {
        method: 'PUT',
        body: data,
      });
    },
    {
      manual: true,
      loadingDelay: loading ? 300 : undefined,
      onSuccess: (data) => {
        if (successMessage && data.success) {
          message.success(data.message || '更新成功');
        }
        config?.onSuccess?.(data);
      },
      onError: (error) => {
        if (errorMessage) {
          message.error(error.message || '更新失败');
        }
        config?.onError?.(error);
      },
      ...restConfig,
    }
  );
};

/**
 * DELETE 请求封装
 * @param url - 请求地址
 * @param config - 请求配置
 * @returns useRequest hook
 */
export const useDelete = <T = any>(
  url: string,
  config?: RequestConfig & Options<ResultData<T>, [string | number]>
) => {
  const { loading = true, errorMessage = true, successMessage = true, ...restConfig } = config || {};
  
  return useRequest(
    async (id: string | number) => {
      return fetchRequest<T>(`${url}/${id}`, {
        method: 'DELETE',
      });
    },
    {
      manual: true,
      loadingDelay: loading ? 300 : undefined,
      onSuccess: (data) => {
        if (successMessage && data.success) {
          message.success(data.message || '删除成功');
        }
        config?.onSuccess?.(data);
      },
      onError: (error) => {
        if (errorMessage) {
          message.error(error.message || '删除失败');
        }
        config?.onError?.(error);
      },
      ...restConfig,
    }
  );
};

/**
 * 通用请求 hook
 * @param service - 请求服务函数
 * @param config - 请求配置
 * @returns useRequest hook
 */
export const useCustomRequest = <T = any, P extends any[] = any[]>(
  service: (...args: P) => Promise<ResultData<T>>,
  config?: RequestConfig & Options<ResultData<T>, P>
) => {
  const { loading = true, errorMessage = true, successMessage = false, ...restConfig } = config || {};
  
  return useRequest(service, {
    loadingDelay: loading ? 300 : undefined,
    onSuccess: (data) => {
      if (successMessage && data.success) {
        message.success(data.message || '操作成功');
      }
      config?.onSuccess?.(data);
    },
    onError: (error) => {
      if (errorMessage) {
        message.error(error.message || '操作失败');
      }
      config?.onError?.(error);
    },
    ...restConfig,
  });
};

export default {
  useGet,
  usePost,
  usePut,
  useDelete,
  useCustomRequest,
};